import router from './router'
import Vue from 'vue'
import store from './vuex'
import NProgress from 'nprogress' // 进度条插件
import 'nprogress/nprogress.css' // 进度条样式
import { getToken } from '@/utils/auth' 
import { filterAsyncRoutes } from '@/utils/asyncRouter.js'
import Router from 'vue-router'
import { mapState, mapGetters, mapMutations, mapActions } from 'vuex'
const routerPush = Router.prototype.push
Router.prototype.push = function push(location) {
  return routerPush.call(this, location).catch(error=> error)
}



NProgress.configure({ showSpinner: false }) // 进度条配置

const whiteList = [] 

router.beforeEach(async (to, from, next) => {
    // console.log(to, from);
    // 进度条开始
    NProgress.start()
     // 获取路由 meta 中的title，并设置给页面标题
    document.title = to.meta.title
    // 获取用户登录的token
    const hasToken = getToken()
    
    // 判断当前用户是否登录
    if (hasToken) {
        console.log("hasToken",hasToken);
        let is404 = to.matched.some(record => {
            if(record.meta.role){
                return record.meta.role.indexOf(store.getters.info.role) === -1
                }
        })
        if (to.path === "/login"){
            sessionStorage.clear();
            next()
        }
        // if (is404 || to.matched.length === 0) {
        //     console.log("not found");
        //     next({path: '/404'})
        //     return false
        // }else 
        if (sessionStorage.role != "" && !sessionStorage.NotRouter) {
            
            !async function getAddRouters () {
                await store.dispatch('getInfo', store.getters.token);
                await store.dispatch('newRoutes', sessionStorage.role)
                await router.addRoutes(store.getters.addRouters)
                next( to.path )
            }()

            
            next()
            NProgress.done()
            console.log("读取路由",to.path,"有"+store.getters.routers.length+"个路由");
            sessionStorage.setItem("NotRouter",true)
            return
        
        } else  {
            store.dispatch('getInfo', store.getters.token);
            console.log("to",to);
            next()
            NProgress.done()
            return
        }
        next()
        console.log("sdfdf",to.path,store.getters.routers);
    } else {
        // 用户未登录
        console.log("未登录");
        // 需要跳转的路由不是whiteList中的路由，直接跳转到登录页
        // next(`/login?redirect=${to.path}`)
        // 结束精度条
        if (whiteList.indexOf(to.path) !== -1) {
            // 需要跳转的路由是否是whiteList中的路由，若是，则直接条状
            next()
        }else if (to.path === '/login') {
            console.log("loging");
            next()
        }else{
            console.log(to.path);
            next({path: `/login?redirect=${to.path}`})
        }
        next()
        NProgress.done()
    }
})

router.afterEach(() => {
    // 结束精度条
    NProgress.done()
})
